<template>
  <div class="app-container flex-cloumn">
    <el-form :model="queryAccountParams" ref="queryRef" v-show="showSearch">
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="账户名称" prop="acc">
            <el-input
                v-model="queryAccountParams.searchAccName"
                clearable
                placeholder="请输入账户名称"
                size="mini"
                :style="{width: '100%'}"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item>
            <el-button type="primary" icon="Search"
                       v-hasPermi="['account:account:list']"
                       style="margin: 3px 3px"
                       size="mini" @click="handleAccountQuery">搜索
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="12" style="margin: 0px 1px">
        <el-button
            type="success"
            style="margin: 3px 3px"
            icon="Plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['account:account:add']"
        >新增
        </el-button>
        <el-button
            type="warning"
            style="margin: 3px 3px"
            icon="Edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['account:account:edt']"
        >修改
        </el-button>
        <el-button
            type="danger"
            style="margin: 3px 3px"
            icon="Delete"
            size="mini"
            :disabled="single"
            @click="handleDelete"
            v-hasPermi="['account:account:del']"
        >删除
        </el-button>
        <el-button
            type="danger"
            style="margin: 3px 3px"
            icon="Plus"
            size="mini"
            :disabled="single3"
            @click="handleStop"
            v-hasPermi="['account:account:stop']"
        >停用
        </el-button>
        <el-button
            type="success"
            style="margin: 3px 3px"
            icon="Plus"
            size="mini"
            :disabled="single4"
            @click="handleStart"
            v-hasPermi="['account:account:start']"
        >启用
        </el-button>
        <el-button
            type="danger"
            style="margin: 3px 3px"
            icon="Edit"
            size="small"
            :disabled="single || alloFlag"
            @click="handleUpdateAllocate"
            v-hasPermi="['account:account:allocate']"
        >授权
        </el-button>
      </el-row>
    </el-form>
    <xTable ref="refAccountTable" refId="refAccountTable" v-loading="loading" :data="accountList" multiple="false"
            @selection-change="handleAccountSelectionChange" class="tableDragger_form">
      <template #columList>
        <el-table-column label="序号" type="index" width="55"/>
        <el-table-column label="账户编号" align="left" prop="accCode"></el-table-column>
        <el-table-column label="账户名称" align="left" prop="accName"></el-table-column>
        <el-table-column label="创建人" align="left" prop="userName"></el-table-column>
        <el-table-column label="权限" width="100" prop="accRight">
          <template #default="scope">
            <dict-tag :options="roleType" :value="scope.row.accRight"/>
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="accStatus" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left" prop="extInfo"></el-table-column>
      </template>
    </xTable>
    <pagination
        style="margin:20px 0 20px 0"
        v-show="accountTotal>0"
        :total="accountTotal"
        v-model:page="queryAccountParams.pageNum"
        v-model:limit="queryAccountParams.pageSize"
        @pagination="getAccountLists"
    />

    <!-- 添加账户对话框 -->
    <el-dialog :close-on-click-modal="false" draggable="true" :title="priceTitle" v-model="accountOpen" destroy-on-close
               width="500px" append-to-body>
      <el-form ref="accountFromRef" :model="accountForm" :rules="accountRules" label-width="110px">
        <el-form-item label="账户编号" prop="accCode">
          <el-input v-model="accountForm.accCode" maxlength="255" :disabled="disableFlag"/>
        </el-form-item>
        <el-form-item label="账户名称" prop="accName">
          <el-input v-model="accountForm.accName" maxlength="100" :disabled="formShow.accName"/>
        </el-form-item>
<!--        <el-form-item label="权限分配" prop="accRight">-->
<!--          <dictCombox v-model="accountForm.accRight" filterKey="1,2" dictType="roleType" size="small"></dictCombox>-->
<!--        </el-form-item>-->
        <el-form-item label="授权" prop="accRight">
          <el-tree
              class="tree-border"
              :data="deptUserOptions"
              show-checkbox
              :default-expanded-keys="defaultUser"
              v-show="accountForm.allocateTreeBorder"
              ref="deptUserPermRef"
              :default-checked-keys="workmates"
              :default-expand-all="deptUserPermExpend"
              node-key="id"
              @check="checkChange"
              empty-text="加载中，请稍候"
              :props="{ label: 'label', children: 'children' }"
          > <template #default="{ node, data }">
                    <span >
                    <span>{{ node.label }}</span>
                      <span v-if="data.type==='u'" >
                        &nbsp;&nbsp;&nbsp;&nbsp;
                      </span>
                    <span v-if="data.type==='u'" >
                      <el-radio-group v-model="treeRadio[data.id.split(':')[1]]" @change="radioChange">
                        <el-radio :label=getReadLabel(data.id)>读权限</el-radio>
                        <el-radio :label=getWriteLabel(data.id)>写权限</el-radio>
                      </el-radio-group>
                    </span>
                  </span>
          </template>
          </el-tree>
        </el-form-item>
        <el-form-item label="备注" v-if="formShow.extInfo">
          <el-input
              v-model="accountForm.extInfo"
              maxlength="300"
              :rows="2"
              type="textarea"
              placeholder="备注"
          />
        </el-form-item>
        <el-form-item label="状态">
          <dictCombox v-model="accountForm.status" dictType="accStatus" :disabled="true" size="small"></dictCombox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改账户对话框 -->
    <el-dialog :close-on-click-modal="false" draggable="true" :title="priceTitle" v-model="accountUpdateOpen"
               width="500px" append-to-body>
      <el-form ref="accountFromRef" :model="accountForm" :rules="accountRules" label-width="110px">
        <el-form-item label="账户编号" prop="accCode">
          <el-input v-model="accountForm.accCode" :disabled="disableFlag"/>
        </el-form-item>
        <el-form-item label="账户名称" prop="accName">
          <el-input v-model="accountForm.accName"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="accountForm.extInfo"
              :rows="2"
              type="textarea"
              placeholder="备注"
          />
        </el-form-item>
        <el-form-item label="状态">
          <dictCombox v-model="accountForm.status" dictType="accStatus" :disabled="true" size="small"></dictCombox>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancelUpdate">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--授权对话框-->
    <el-dialog :title="allocateTitle" v-model="allocateOpen" draggable="true"
               :close-on-click-modal="false" width="1000px" :height="dialogHeight" append-to-body>
      <el-row :gutter="20">
        <!--部门数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input
                v-model="deptName"
                placeholder="请输入部门名称"
                clearable
                prefix-icon="el-icon-search"
                style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
                :data="deptOptions"
                :props="{ label: 'label', children: 'children' }"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="deptTreeRef"
                default-expand-all
                @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <!--用户数据-->
        <el-col :span="20" :xs="24">
          <el-form :model="allocateQueryParams" ref="allocateQueryRef" :inline="true">
            <el-row>
              <el-form-item label="用户编号" prop="userName">
                <el-input
                    v-model="allocateQueryParams.userName"
                    placeholder="请输入用户编号"
                    clearable
                    @keyup.enter="handleAllocateQuery"
                />
              </el-form-item>

              <el-form-item label="用户名称" prop="nickName">
                <el-input
                    v-model="allocateQueryParams.nickName"
                    placeholder="请输入用户名称"
                    clearable
                    @keyup.enter="handleAllocateQuery"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" size="small" @click="handleAllocateQuery">搜索</el-button>
              </el-form-item>
            </el-row>
          </el-form>

          <el-row :gutter="10" class="mb8" style="margin-top:5px">
            <el-col :span="1.5">
              <el-button
                  type="success"
                  icon="Edit"
                  size="small"
                  :disabled="allocateMultiple || adminShow"
                  v-show="rows[0].accRight >= 2"
                  @click="handleWriteDefault"
              >写权限
              </el-button>
            </el-col>

            <el-col :span="1.5">
              <el-button
                  type="success"
                  icon="Edit"
                  size="small"
                  v-show="rows[0].accRight >= 1"
                  :disabled="allocateMultiple || adminShow"
                  @click="handleReadDefault"
              >读权限
              </el-button>
            </el-col>

            <el-col :span="1.5">
              <el-button
                  type="success"
                  icon="Edit"
                  size="small"
                  :disabled="allocateMultiple || adminShow"
                  @click="handleNoneDefault"
              >取消权限
              </el-button>
            </el-col>

          </el-row>

          <xTable ref="allocateUserTable" refId="allocateUserTable"
                  v-loading="allocateLoading" :data="allocateUserList"
                  :style="{height:screenHeight , overflow:'auto'}"
                  @selection-change="allocateUserHandleSelectionChange">
            <template #columList>
              <el-table-column label="用户编号" align="center" prop="userName" :show-overflow-tooltip="true"/>
              <el-table-column label="用户名称" align="center" prop="nickName" :show-overflow-tooltip="true"/>
              <el-table-column label="所属部门" align="center" prop="deptName" :show-overflow-tooltip="true"/>
              <el-table-column label="账户名称" align="center" prop="accName" :show-overflow-tooltip="true"/>
              <el-table-column label="读写权限" align="center" prop="accRight" class-name="small-padding fixed-width">
                <template #default="scope">
                  <dict-tag :options="roleType" :value="scope.row.status"/>
                </template>
              </el-table-column>
            </template>
          </xTable>
          <pagination
              v-show="allocateUserTotal > 0"
              :total="allocateUserTotal"
              v-model:page="allocateQueryParams.pageNum"
              v-model:limit="allocateQueryParams.pageSize"
              @pagination="getAllocateUser"
          />
        </el-col>
      </el-row>
    </el-dialog>

  </div>
</template>

<script setup name="Selfaccount">
import {ref} from "vue";
import {
  getAccountList,
  deleteAccount,
  updateAccount,
  saveAccount,
  getAccountUserAndDpetPerm,
  updateAccountPerm,
  listAllocateUser,
  updateUserAuthor,
  queryTtradeCountByAccId
} from '@/api/account/accountmanage';

import {treeselectuser, treeselect} from "@/api/system/dept";

const {proxy} = getCurrentInstance();
// 账户列表
const accountList = ref([]);
const accountOpen = ref(false);
const accountUpdateOpen = ref(false);
const {accStatus} = proxy.useDict("accStatus");
const {roleType} = proxy.useDict('roleType');
const priceTitle = ref('');
const deptUserOptions = ref([]);
const loading = ref(false);
const showSearch = ref(true);
const disableFlag = ref(false);
const ids = ref([]);
const names = ref([]);
const deptUserPermRef = ref(null);
const alloFlag = ref(false)

const deptUserPermExpend = ref(false);
//数据
const rows = ref([]);
const single = ref(true);
const multiple = ref(true);
const single3 = ref(true);
const single4 = ref(true);
const accountTotal = ref(0);
const action = ref('');
import store from '@/store'
import {isNotVoid} from "../../../utils/util";

const defaultUser = ref(['u:' + store.getters.user.userId])


//授权对话框
const allocateUserList = ref([]);
const allocateTitle = ref("");
const allocateOpen = ref(false);
const allocateLoading = ref(true);
const allocateUserTotal = ref(0);
const deptOptions = ref(undefined);
const deptName = ref("");
const userIds = ref([]);
const adminShow = ref(false);
const allocateSingle = ref(true);
const allocateMultiple = ref(true);

const screenHeight = ref(document.documentElement.clientHeight - 350 + "px");
const dialogHeight = ref(document.documentElement.clientHeight - 200 + "px");

const deptId = ref();

const workmates = ref([]);

const data = reactive({
  treeRadio:[],
  accountRules: {
    accName: [{required: true, message: "账户名称不能为空", trigger: "change"}],
    accCode: [{required: true, message: "账户编号不能为空", trigger: "change"}],
    accRight: [{required: true, message: "授权类型不能为空", trigger: "change"}],
  },
  accountForm: {
    accId: null,
    accCode: null,
    accName: null,
    status: null,
    userName: null,
    extInfo: null,
    allocateId: null,
    allocateTreeBorder: true,
    accRight: '2'
  },
  queryAccountParams: {
    pageNum: 1,
    pageSize: 20,
    searchAccName: null,
    acc: null,
  },
  formShow: {
    accId: true,
    accCode: true,
    accName: true,
    status: true,
    userName: true,
    extInfo: true,
    allocateId: true,
    allocateTreeBorder: true,
    accRight: true
  },
  allocateQueryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: undefined,
    deptName: undefined,
    userName: undefined,
    nickName: undefined,
    accId: undefined
  },

});

const {
  queryAccountParams,
  accountForm,
  accountRules,
  formShow,
  allocateQueryParams,
  treeRadio
} = toRefs(data);

/** 查询按钮 */
function handleAccountQuery() {
  getAccountLists();
}

/** 查询账户列表 */
function getAccountLists() {
  loading.value = true;
  getAccountList(proxy.lsh.assign(queryAccountParams.value, {flag: '1'})).then(response => {
    accountList.value = response.list;
    accountTotal.value = response.total;
    loading.value = false;
  });
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选部门树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 查询部门下拉树结构 */
function getTreeselect() {
  treeselect().then(response => {
    deptOptions.value = response.data;
    handleNodeClick({id: store.getters.user.deptId});
  });
};

/** 节点单击事件 */
function handleNodeClick(data) {
  allocateQueryParams.value.deptId = data.id;
  handleAllocateQuery();
};

//点击授权里的搜索按钮
function handleAllocateQuery() {
  allocateQueryParams.value.pageNum = 1;
  getAllocateUser();
}


function allocateUserHandleSelectionChange(selection) {
  userIds.value = selection.map(item => item.userId);
  if (selection.length != 0) {
    deptId.value = selection[0].deptId;
  }
  if (userIds.value.includes(store.getters.user.userId) === true||userIds.value.includes(1) === true) {
    adminShow.value = true
  } else {
    adminShow.value = false
  }
  allocateSingle.value = selection.length != 1;
  allocateMultiple.value = !selection.length;
}

/**账户 新增按钮操作 */
function handleAdd() {
  reset();
  defaultUser.value = ['u:' + store.getters.user.userId];
  let tempWorkMates = [];
  let a = proxy.treeFindPath(deptUserOptions.value,node => {
    if(node.id == defaultUser.value){
      return true;
    }
  });
  treeRadio.value=[];
  a[a.length -2].children.forEach(item => {
    if(item.id.search("u:") != -1){
      tempWorkMates.push(item.id);
      let uId=item.id.split(':')[1];
      if(uId==store.getters.user.userId){
        treeRadio.value[uId]=uId+'-2';
      }else{
        treeRadio.value[uId]=uId+'-1';
      }
    }
  })
  workmates.value = tempWorkMates;
  accountForm.value.allocateTreeBorder = true;
  deptUserPermExpend.value = false;
  formShow.value.extInfo = true;
  formShow.value.accName = false;

  disableFlag.value = false;
  accountOpen.value = true;
  priceTitle.value = "新增账户";
  accountForm.value.accName = '';
  accountForm.value.status = '1';
  action.value = 'add';
}

/** 授权按钮操作 */
function handleUpdateAllocate() {

  // reset();
  // defaultUser.value=['u:'+store.getters.user.userId];

  // deptUserPermExpend.value = true;
  // formShow.value.extInfo = false;
  // formShow.value.accName = true;
  // accountForm.value.allocateTreeBorder=true;
  // disableFlag.value = true;

  // action.value = 'allocate';
  // accountOpen.value = true;
  // accountForm.value.accCode=rows.value[0].accCode;
  // accountForm.value.accId = rows.value[0].accId;
  // accountForm.value.accName = rows.value[0].accName;
  // accountForm.value.status = String(rows.value[0].status);
  // accountForm.value.creater = rows.value[0].userId;
  // priceTitle.value = "账户授权";

  //  const arrs =  getAccountUserAndDpetPerm(accountForm.value).then(response =>{
  //   return response;
  // })

  //   //回显
  // nextTick(() =>{
  // arrs.then((res) => {
  //   res.forEach((element) =>{
  //   nextTick(() =>{
  //     deptUserPermRef.value.setChecked(element,true,false)
  //       })
  //   })
  //   })
  // });

  allocateOpen.value = true;
  allocateTitle.value = "授权";
  allocateQueryParams.value.accId = rows.value[0].accId;
  getTreeselect();
}


function getAllocateUser() {
  allocateLoading.value = true;
  listAllocateUser(allocateQueryParams.value).then(response => {
    allocateUserList.value = response.rows;
    allocateUserList.value.forEach(element => {
      element.accName = rows.value[0].accName;
    })
    allocateUserTotal.value = response.total;
    allocateLoading.value = false;
  });
}


/**
 *
 * 账户  修改按钮操作
 * */
function handleUpdate() {
  if (rows.value[0].accRight === '1') {
    proxy.$modal.alertError("没有权限修改该数据");
    return;
  }
  reset();
  action.value = 'update';
  disableFlag.value = true;
  accountForm.value.allocateTreeBorder = false;
  accountUpdateOpen.value = true;
  accountForm.value.accCode = rows.value[0].accCode;
  accountForm.value.accId = rows.value[0].accId;
  accountForm.value.accName = rows.value[0].accName;
  accountForm.value.status = String(rows.value[0].status);
  accountForm.value.creater = rows.value[0].userId;
  priceTitle.value = "修改账户信息";
}

// 停用
function handleStop() {
  if (rows.value[0].accRight === '1') {
    proxy.$modal.alertError("没有权限修改该数据");
    return;
  }
  accountForm.value.accId = rows.value[0].accId;
  accountForm.value.accName = rows.value[0].accName;
  accountForm.value.status = 2;
  updateAccount(accountForm.value).then(response => {
    if (response.success) {
      proxy.$modal.msgSuccess("修改成功");
      accountUpdateOpen.value = false;
      queryAccountParams.value.searchAccName = null;
      reset();
      getAccountLists();
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });
}


/** 写权限 */
function handleWriteDefault() {
  handleAuth('2');
}

/** 读权限 */
function handleReadDefault() {
  handleAuth('1');
}

/** 无权限 */
function handleNoneDefault() {
  handleAuth('0');
}

/** 分配权限操作 */
function handleAuth(accRight) {
  var params = {};
  params.accId = rows.value[0].accId;
  params.deptId = deptId.value;
  params.userIds = userIds.value;
  params.accRight = accRight;

  updateUserAuthor(params).then(response => {
    if (response.success) {
      proxy.$modal.msgSuccess("设置成功");
      getAllocateUser();
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });

}

// 启用
function handleStart() {
  if (rows.value[0].accRight === '1') {
    proxy.$modal.alertError("没有权限修改该数据");
    return;
  }
  accountForm.value.accId = rows.value[0].accId;
  accountForm.value.accName = rows.value[0].accName;
  accountForm.value.status = 1;
  updateAccount(accountForm.value).then(response => {
    if (response.success) {
      proxy.$modal.msgSuccess("修改成功");
      accountUpdateOpen.value = false;
      queryAccountParams.value.searchAccName = null;
      reset();
      getAccountLists();
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });
}

/**
 *
 * 修改/新增   保存操作
 * */
function submitForm() {
  proxy.$refs["accountFromRef"].validate(valid => {
    if (valid) {
      if (action.value == 'update') {
        updateAccount(accountForm.value).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess("修改成功");
            accountUpdateOpen.value = false;
            queryAccountParams.value.searchAccName = null;
            reset();
            getAccountLists();
          } else {
            queryAccountParams.value.searchAccName = null;
            proxy.$modal.msgError(response.msg);
          }
        });
      } else if (action.value == 'add') {
        let addParam =proxy.lsh.cloneDeep(accountForm.value);
        let radioArray={};
        proxy.lsh.forEach(treeRadio.value,function(val,ky){
          if(val!=undefined&&val!=null&&isNotVoid(val.split("-")[1])){
            radioArray[val.split("-")[0]]=val.split("-")[1];
          }
        })
        proxy.lsh.assign(addParam, {'accRightUser': getTreeChecks().join(','),'accRight':JSON.stringify(radioArray)});
        saveAccount(addParam).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess("新增成功");
            accountOpen.value = false;
            queryAccountParams.value.searchAccName = null;
            reset();
            getAccountLists();
          } else {
            queryAccountParams.value.searchAccName = null;
            proxy.$modal.msgError(response.msg);
          }
        });
      } else if (action.value == 'allocate') {
        let addParam = accountForm.value;
        proxy.lsh.assign(addParam, {'accRightUser': getTreeChecks().join(',')});
        updateAccountPerm(addParam).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess("授权成功");
            accountOpen.value = false;
            queryAccountParams.value.searchAccName = null;
            reset();
            getAccountLists();
          } else {
            queryAccountParams.value.searchAccName = null;
            proxy.$modal.msgError(response.msg);
          }
        })
      }
    }
  });
}


/**
 *
 * 多选框  选中数据
 * */
function handleAccountSelectionChange(selection) {
  if (selection.length === 1 && (selection[0].accRight == '2' || store.getters.user.userId == '1')) {
    alloFlag.value = false;
  } else {
    alloFlag.value = true;
  }

  if (selection.length == 0) {
    ids.value = [];
    names.value = [];
  } else {
    ids.value = selection.map(item => item.accId);
    names.value = selection.map(item => item.accName);
    rows.value = selection.map(item => item);
  }
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  if (selection.length == 1) {
    if (rows.value[0].status === 1) {
      single3.value = false
    }
    if (rows.value[0].status === 2 || rows.value[0].status === 0) {
      single4.value = false
    }
  } else {
    single3.value = true;
    single4.value = true;
  }
}

/** 删除按钮操作 */
function handleDelete() {
  if (rows.value[0].accRight === '1') {
    proxy.$modal.alertError("没有权限删除该数据");
    return;
  }
  var params = {
    accId: rows.value[0].accId
  };
  queryTtradeCountByAccId(params).then(response => {
    if (response > 0) {
      proxy.$modal.alertError("该账号有关联交易，请检查!");
    } else {
      deletetheAccount(params);
    }
  });
}


function deletetheAccount(params) {
  const accName = names.value;
  proxy.$modal.confirm('是否确认删除账户名称为 "' + accName + '"的数据项？').then(function () {
    return deleteAccount(params);
  }).then(() => {
    queryAccountParams.value.searchAccName = null;
    getAccountLists();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 取消修改按钮 */
function cancelUpdate() {
  accountUpdateOpen.value = false;
  reset();
}

/** 取消添加按钮 */
function cancel() {
  accountOpen.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  accountForm.value = {
    accId: null,
    accCode: null,
    accName: null,
    status: null,
    extInfo: null,
    create: null,
    accRight: '1'
  };
  proxy.resetForm("accountFromRef");
}

// ============权限分配
/** 查询部门用户下拉树结构 */
function getTreeselectuser() {
  treeselectuser().then(response => {
    deptUserOptions.value = response.data;
  });
};


function getTreeChecks() {
  // 目前被选中的菜单节点
  let checkedKeys = deptUserPermRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = deptUserPermRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

getTreeselectuser();
getAccountLists();

function checkChange(data, option) {
  let checkStatus=false;
  option.checkedKeys.forEach(function(option,index) {
    if(option==data.id){
      checkStatus=true;
    }
  });
  if (data.id === defaultUser.value[0]) {
    deptUserPermRef.value.setChecked(data, true, true);
    treeRadio.value[data.id.split(":")[1]]=data.id.split(":")[1]+'-2';
  }else{
    let uId=data.id.split(":")[1];
    if(checkStatus){
      if(treeRadio.value[uId]!=undefined&&treeRadio.value[uId].split('-')[1]=='2') {
        treeRadio.value[uId] = uId + '-2';
      }else{
        treeRadio.value[uId] = uId + '-1';
      }
      //如果为其他节点时处理子节点 读写
      let nodeArray=[];
      putChildOfTree(nodeArray,data);
      proxy.lsh.forEach(nodeArray, function (opt) {
        if(opt.id.split(':')[0]=='u'){
          let uId2=opt.id.split(':')[1];
          if((treeRadio.value[uId2]!=undefined&&treeRadio.value[uId2].split('-')[1]=='2')||uId2==defaultUser.value[0]) {
            treeRadio.value[uId2] = uId2 + '-2';
          }else{
            treeRadio.value[uId2] = uId2 + '-1';
          }
        }
      });
    }else{
      treeRadio.value[uId]=uId+'-0';
      //如果为其他节点时处理子节点 读写
      let nodeArray=[];
      putChildOfTree(nodeArray,data);
      proxy.lsh.forEach(nodeArray, function (opt) {
        if(opt.id.split(':')[0]=='u'){
          let uId2=opt.id.split(':')[1];
          if(uId2===defaultUser.value[0].split(":")[1]) {
            deptUserPermRef.value.setChecked(defaultUser.value[0], true, true);
            treeRadio.value[uId2] = uId2 + '-2';
          }else{
            treeRadio.value[uId2] = uId2 + '-0';
          }
        }
      });
    }

  }
}
function getReadLabel(key){
  let uId=key.split(":")[1];
  return uId+'-1';
}
function getWriteLabel(key){
  let uId=key.split(":")[1];
  return uId+'-2';
}
function radioChange(value){
  let uId=value.split("-")[0];
  if(uId==store.getters.user.userId){
    treeRadio.value[uId]=uId+'-2';
  }
  deptUserPermRef.value.setChecked({id:'u:'+uId}, true, true);
}
function putChildOfTree(nodeArray,data){
  if(data.children!=undefined&&data.children!=null&&data.children.length>0) {
     proxy.lsh.forEach(data.children, function (childData) {
      nodeArray.push(childData);
      putChildOfTree(nodeArray,childData);
    });
  }
}
</script>
